# -*- coding:utf-8 -*-
from django.db import models
from django import forms
from django.forms import widgets
from django.template import loader, Context
from django.db.models.loading import get_app, get_model
from django.conf import settings
#from homesite.bugs.globals import project_id

#from homesite.bugs.models import Task

def get_id(model, value):
  if not value:
    return ''
  tags = get_app('bugs')
  from homesite.bugs.utils import normalize_title
  obj_list = model.objects.filter(norm_value__exact=normalize_title(value))
  if len(obj_list):
    return int(obj_list[0].id)
  else:
    obj = model(value=value)
    obj.save()
    return int(obj.id)

class TagsFormWidget(widgets.Widget):  

  def __init__(self, *args, **kwargs):
    self.field_name = 'tags'
    self.model = get_model('bugs', 'Tag')
    self.choices = ()
    #self.is_required = is_required
    #self.maxlength = self.model._meta.get_field('value').maxlength
    #self.validator_list = [self.isValidLength] + validator_list
    super(TagsFormWidget, self).__init__(*args, **kwargs)
    

  def value_from_datadict(self, data, files, name):
    value = [] 
    if data.has_key(self.field_name):
      return [get_id(self.model, v) for v in data.getlist(self.field_name) if v != '']
    else:  
      return data.get(name, None)

  
   
  def render(self, name, value=None, attrs=None):
    #model = get_model('tagsfield', 'Tag')
    initial_tags = []
    if value:
      ids = [id for id in value if type(id) == long]
      if ids:
        initial_tags.extend(list(self.model.objects.filter(id__in=ids)))
      strs = [s for s in value if type(s) != long] #int
      if strs:
        initial_tags.extend(strs)
    template = loader.get_template('bugs/tag_widget.html')
    context = Context({
      'field_name': 'tags',  #self.field_name,
      'tags': self.model.objects.all(),  
      'initial_tags': initial_tags,
      'style_url': hasattr(settings, 'STYLE_URL') and settings.STYLE_URL or '/media/css/',
      'js_url': hasattr(settings, 'JS_URL') and settings.JS_URL or '/media/js/',
      'maxlength':'32', #self.maxlength,
      #'project_id': project_id,# getattr(TaskForm,'project'),
    })
    return template.render(context)
    

	
class TagsFormField(forms.Field):
  widget = TagsFormWidget
  requires_data_list = True
  
  def __init__(self, field_name, queryset, model=None, is_required=False, validator_list=[], *args, **kwargs):
    self.field_name = field_name
    self.model = model or get_model('bugs', 'Tag')
    self.is_required = is_required
    self.maxlength = self.model._meta.get_field('value').max_length
    #self.validator_list = [self.isValidLength] + validator_list
    super(TagsFormField, self).__init__(*args, **kwargs)
  
  def clean(self, data): 
    super(TagsFormField, self).clean(data) 
    return data
  


    
class TagsField(models.ManyToManyField):
  def get_manipulator_field_objs(self):
    return [TagsFormField]



  def get_internal_type(self):
    return "TagsField"


 
  def formfield(self, **kwargs):
    #defaults = {'form_class': TagsFormField, 'queryset': self.rel.to._default_manager.complex_filter(self.rel.limit_choices_to)}
    #tags = get_app('tagsfield')
    defaults = {'form_class': TagsFormField, 'field_name':'tags'}
    defaults.update(kwargs)
    # If initial is passed in, it's a list of related objects, but the
    # MultipleChoiceField takes a list of IDs.
    if defaults.get('initial') is not None:
      defaults['initial'] = [i._get_pk_val() for i in defaults['initial']]
    return super(TagsField, self).formfield(**defaults)
  
  
    
  def prepare_field_objs_and_params(self, manipulator, name_prefix):
    field_objs, params = super(TagsField, self).prepare_field_objs_and_params(manipulator, name_prefix)
    params['model'] = self.rel.to
    return field_objs, params


    
  def flatten_data(self, follow, obj=None):
    new_data = {}
    if obj:
      new_data[self.name] = [int(instance.id) for instance in getattr(obj, self.name).all()]
    return new_data

